import configs from '@/common/config.js'
import http from '@/common/api.js';
// #ifdef H5
import {
	wxAuthorize
} from '@/utils/wxauth.js'
import jwx from '@/utils/jwx.js'
// #endif

const oss = (url) => {
	if (!url) {
		return ''
	}
	if (typeof url === 'string') {
		if ((/^(http|https):\/\/.+/.test(url))) {
			return url
		} else if ((/^(data:image).+/.test(url))) {
			// return configs.imgUrl + uni.getStorageSync('project').user_logo_image
			return url
		} else {
			return configs.imgUrl + url
		}
	} else {
		let arr = []
		for (let i = 0; i < url.length; i++) {
			if ((/^(http|https):\/\/.+/.test(url[i]))) {
				arr.push(url[i])
			} else {
				arr.push(configs.imgUrl + url[i])
			}
		}
		return arr
	}
}

const skip = (url, events = {}, success)=>{
  uni.navigateTo({
    url,
    events,
    success
  })
}
const back = (delta = 1) => {
  uni.navigateBack({
    delta: delta
  })
}

const authTo = (url) => {
	if (uni.getStorageSync('token')) {
		uni.navigateTo({
			url: url
		});
	} else {
		uni.navigateTo({
			url: configs.login
		});
	}
}

const login = () => {
	uni.navigateTo({
		url: configs.login
	});
}

const toast = (word) => {
	uni.$u.toast(word);
}

const copy = (content) => {
	uni.setClipboardData({
		data: content,
		success: function() {
			uni.$u.toast('复制成功')
		},
		fail: function() {
			uni.$u.toast('复制失败')
		}
	});
}

const calculateRemainingTime = (timestamp) => {
  // 将时间戳转换为毫秒数
  const now = Date.now();
  const targetTime = new Date(timestamp).getTime();

  // 计算剩余时间（毫秒）
  let remainingTime = targetTime - now;

  // 计算剩余小时数和分钟数
  const hours = Math.floor(remainingTime / (1000 * 60 * 60));
  remainingTime %= (1000 * 60 * 60);
  const minutes = Math.floor(remainingTime / (1000 * 60));

  return { hours, minutes };
}

const calculateElapsedTime = (timestamp) => {
  // 将时间戳转换为毫秒数
  const now = Date.now();
  const targetTime = new Date(timestamp).getTime();

  // 计算已经过去的时间（毫秒）
  let elapsedTime = now - targetTime;

  // 计算已经过去的小时数和分钟数
  const hours = Math.floor(elapsedTime / (1000 * 60 * 60));
  elapsedTime %= (1000 * 60 * 60);
  const minutes = Math.floor(elapsedTime / (1000 * 60));

  return  hours + '时' + minutes + '分';
}

const chooseLocation = () => {
	return new Promise((resolve, reject) => {
		uni.chooseLocation({
			success: function(res) {
				http.post('/getLocation', {
					lng: res.longitude,
					lat: res.latitude,
				}).then(response => {

					if (response.code == 1) {
						console.log(response)
						let province, city, name;
						province = response.data.province;
						if (response.data.city.length == 0) {
							city = response.data.province
						} else {
							city = response.data.city
						}
						console.log(city)
						name = res.address
							console.log(name)
						let data = {
							province: province,
							city: city,
							district:response.data.district,
							lng: res.longitude,
							lat: res.latitude,
							name: name
						}
						resolve(data)
					}
				}).catch(e => {
					let data = {
						province: '河南省',
						city: '郑州市',
						lat: '34.74725',
						lng: '113.62493'
					}
					reject(data)
				})
			},
			fail: (e) => {
				let data = {
					province: '河南省',
					city: '郑州市',
					lat: '34.74725',
					lng: '113.62493'
				}
				reject(data)
			}
		});
	})

}

const pay = (data) => {
	return new Promise((resolve, reject) => {
		if (data.paytype == 0) {
			// 支付宝支付
			uni.requestPayment({
				provider: 'alipay',
				orderInfo: data.pay, //支付宝订单数据
				success: function(res) {
					resolve()
				},
				fail: function(err) {
					reject()
				}
			});
		} else if (data.paytype == 1) {
			// 微信支付APp
			// let datb = JSON.parse(data.pay)
			uni.requestPayment({
				provider: 'wxpay',
				orderInfo: data,
				success: (e) => {
					resolve()

				},
				fail: (e) => {
					reject(e)

				}
			})

		} else if (data.paytype == 2) {
			// 微信小程序
			uni.requestPayment({
				appId: data.appId,
				nonceStr: data.nonceStr,
				package: data.package,
				paySign: data.paySign,
				signType: data.signType,
				timeStamp: data.timeStamp,
				success: (e) => {
					resolve(e)
				},
				fail: (e) => {
					reject(e)
				}
			})
		} else if (data.paytype == 3) {
			// 微信支付公众号
			// #ifdef H5
			jwx.wxpay({
				data: data,
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
			// #endif

		} else if (data.paytype == 4) {
			// 余额支付
			resolve()
		}
	})

}

const utils = Vue => {
	Vue.prototype.$authTo = authTo
	Vue.prototype.$oss = oss
	Vue.prototype.$copy = copy
	Vue.prototype.$toast = toast
	Vue.prototype.$pay = pay
	Vue.prototype.$login = login
	Vue.prototype.$uploadUrl = configs.baseUrl + '/api/upload'
	Vue.prototype.$chooseLocation = chooseLocation
	Vue.prototype.calculateRemainingTime = calculateRemainingTime
	Vue.prototype.calculateElapsedTime = calculateElapsedTime
	Vue.prototype.$skip = skip
	Vue.prototype.$back = back
	
	// #ifdef H5
	Vue.prototype.$wxOauth = wxAuthorize
	Vue.prototype.$jwx = jwx
	// #endif

	// #ifdef APP
	Vue.prototype.$safeTop = uni.getSystemInfoSync().statusBarHeight;
	// #endif
	// #ifdef MP-WEIXIN
	Vue.prototype.$safeTop = uni.getMenuButtonBoundingClientRect().top + 'px'
	Vue.prototype.$menuH = uni.getMenuButtonBoundingClientRect().height + 'px'
	// #endif
	// #ifdef H5
	Vue.prototype.$safeTop = uni.getSystemInfoSync().statusBarHeight + 20 + 'px';
	// #endif

}


export default utils